<template>
  <div class="content-wrap content-container" v-loading="loading">
    <!-- 搜索区域 -->
    <el-form class="search-wrap" v-model="searchFormData">
      <el-form-item
        class="search-wrap-item"
        label="标题关键字："
        prop="projectTitle"
      >
        <el-input
          width="160px"
          placeholder="请输入标题关键字"
          v-model="searchFormData.projectTitle"
          clearable
          @input="getAllReviewRequirement"
        ></el-input>
      </el-form-item>
      <el-form-item class="search-wrap-item" label="时间：" prop="time">
        <el-date-picker
          style="width: 240px"
          type="daterange"
          unlink-panels
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :value-on-clear="null"
          v-model="searchFormData.time"
          @change="getAllReviewRequirement"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="createRequirementClick"
          >创建需求</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 待审核需求列表 -->
    <div class="card-wrap-table">
      <el-table :data="allReviewRequirement" border style="width: 100%;height: 100%;">
        <el-table-column
          fixed
          type="index"
          label="序号"
          width="60"
          align="center"
        ></el-table-column>
        <el-table-column label="创建人" prop="requirementCreateName" width="120" align="center">
          <template #="{ row }">
            <span>{{ row.requirementCreateName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="需求名称" prop="requirementName" min-width="460">
          <template #="{ row }">
            <p class="table-requirement-name" @click="handleRowClick(row.ID)">{{ row.requirementName }}</p>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createAt" width="120" align="center">
            <template #="{ row }">
                <span>{{ tableTimeDate(row.createAt) }}</span>
            </template>
        </el-table-column>
        <el-table-column label="预计上线时间" prop="onlineTime" width="120" align="center">
            <template #="{ row }">
                <span>{{ tableTimeDate(row.onlineTime) }}</span>
            </template>
        </el-table-column>
        <!-- <el-table-column label="附件" prop="itemRequirementWorldDraft" min-width="60" align="center">
          <template #="{ row }">
            <span>{{ row.itemRequirementWorldDraft == "" ? "/" : "" }}</span>
            <div class="table-download" v-if="row.itemRequirementWorldDraft !== ''" @click="handleDownLoad(row.itemRequirementWorldDraft)">
                <el-icon :size="16"><Download /></el-icon>
            </div>
          </template>
        </el-table-column> -->
        <el-table-column 
            label="审核状态" 
            prop="itemRequirementIsEnter" 
            width="120" 
            align="center">
          <template #="{ row }">
            <span
              :style="{
                color: enterStatus(row.itemRequirementIsEnter).bgColor,
              }"
              >{{ enterStatus(row.itemRequirementIsEnter).content }}</span
            >
          </template>
        </el-table-column>
       <!--  <el-table-column label="技术负责人" prop="requirementBossName" width="160" align="center">
          <template #="{ row }">
            <el-dropdown
              :hide-on-click="false"
              placement="bottom"
              @command="handleCommand"
            >
              <span class="el-dropdown-link">
                {{
                  row.requirementBossName === ""
                    ? "无"
                    : row.requirementBossName
                }}&nbsp;&nbsp;<el-icon class="el-icon--right"
                  ><arrow-down
                /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    :disabled="row.itemRequirementIsEnter !== 3"
                    :command="{ type: 1, command: item.nickName, id: row.ID }"
                    v-for="(item, index) in reviewNameOptions"
                    :key="index"
                    >{{ item.nickName }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              :disabled="row.itemRequirementIsEnter == 2"
              @click="handleOpenDialog(row.ID)"
            >
              审核
            </el-button>
            <!-- 审核不通过，可查看原因，待审核为禁用状态 -->
            <el-button
              size="small"
              type="primary"
              :disabled="(row.itemRequirementIsEnter == 1 && row.itemRequirementReview.length == 0)"
              @click="handleReviewEnterMsg(row.ID)"
            >
              审核记录
            </el-button>
           <!--  <el-button size="small" @click="closeFatherStatus(row.ID)">
              关闭
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 审核需求弹窗 -->
    <el-dialog v-model="dialogReviewVisible" title="审核需求" width="1200" :close-on-click-modal="false">
      <el-form>
        <el-form-item>
          <CommonRequirementInfoVue :isRequirementID="isRequirementID" :clearData="clearData"></CommonRequirementInfoVue>
        </el-form-item>
        <el-form-item label="评语：">
          <el-input
            maxlength="200"
            placeholder="请输入评语..."
            show-word-limit
            type="textarea"
            v-model="requirementMsg"
          />
        </el-form-item>
        <el-form-item label="评分：">
          <el-input-number
            style="width: 100px;"
            class="mx-4"
            min="0"
            max="500"
            controls-position="right"
            v-model="reViewContentNumber"
          />
        </el-form-item>
      </el-form>
      <!-- <el-dialog v-model="dialogReviewNameVisible" style="width: 300px;">
        <p>技术负责人：</p>
        <el-select v-model="isReviewName" placeholder="请选择技术负责人" style="width: 180px">
            <el-option
                v-for="item in reviewNameOptions"
                :key="item.uuid"
                :label="item.nickName"
                :value="item.nickName"
            />
        </el-select>
        <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogReviewNameVisible = false">取消</el-button>
          <el-button type="primary" @click="handleReviewName">确定</el-button>
        </div>
      </template>
      </el-dialog> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleReview(2)">不通过</el-button>
          <el-button type="primary" @click="handleReview(3)"> 通过 </el-button>
        </div>
      </template>
    </el-dialog>

     <!-- 查看审核记录弹窗 -->
     <el-dialog style="width: 600px;" title="审核记录" :close-on-click-modal="false" v-model="dialogRecordVisible" @close="handleCloseDiglog">
      <el-timeline style="max-width: 560px; max-height: 500px; padding: 20px; overflow-y: auto;">
        <el-timeline-item
          v-for="(record, index) in recordData"
          :key="index"
          :timestamp="`审核时间：${tableTimeDateMsg(record.reviewDate)}`"
          :color="record.isEnter == 1 ? '#F56C6C' : record.isEnter == 2 ? '#E6A23C' :  record.isEnter == 3 ? '#67C23A' : '#F56C6C'"
          placement="top"
        >
        <el-card>
          <div class="record-title">
            <p>
              <span style="font-weight: bold;">审核人：</span>
              <span>{{ record.reViewUserName }}</span>
            </p>
            <p>
              <span style="font-weight: bold;">审核结果：</span>
              <span :style="{ color: enterStatus(record.isEnter).bgColor}">{{ enterStatus(record.isEnter).content }}</span>
            </p>
            <p>
              <span style="font-weight: bold;">评分：</span>
              <span>{{ record.reViewContentNumber }}</span>
            </p>
          </div>
          <!-- 评语 -->
          <div>
            <span style="font-weight: bold;">&nbsp;&nbsp;评语：</span>
            {{ record.reViewContent }} 
          </div>
          <!-- 需求草稿文档下载 -->
          <div class="info-file-box" v-if="record.worldUrl !== ''">
              <p class="info-content-title"><span style="font-weight: bold;">需求草稿：</span></p>
              <ul class="info-file-ul">
                  <li class="info-file-item" v-for="(item, index) in handleRecordFiles(record.worldUrl)" :key="index" @click="handleDownloadFile(item, baseUrl)">
                    <el-icon :size="12"><Document /></el-icon>
                    <span style="font-size: 12px;">{{ item.name }}</span>
                  </li>
              </ul>
          </div>
        </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>

    <!-- 需求详情弹窗 -->
    <el-dialog style="width: 1200px;" :close-on-click-modal="false" v-model="dialogInfoVisible" @close="dialogInfoVisible = false"  @closed="dialogInfoVisible = false">
        <CommonRequirementInfoVue :isRequirementID="isRequirementID" :clearData="clearData"></CommonRequirementInfoVue>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { ElForm } from "element-plus";
import {
  putCloseRequirementStatus,
  getNewFatherRequirementStatus,
  PostRequirement,
  PostReviewRequirementMsg,
  GetEnterRequirement,
  GetRequirementEnterMsg,
} from "@/api/newDemands/index";
import { tableTimeDate, enterStatus, fatherStatus, tableTimeDateMsg, handleDownloadFile, handleFileName } from "@/utils/utils";
import useCommonDataStore from "@/store/common/common";
import CommonRequirementInfoVue from "../comomRequirementInfo.vue";

let router = useRouter();
let useCommonStore = useCommonDataStore();
const loading = ref(false);
const userAuthId = ref<any>(null); //当前用户权限id
const searchFormData = ref({
  projectTitle: "",
  time: [null, null],
});

const dialogReviewVisible = ref(false); //审核需求弹窗

const isRequirementID = ref<any>(null); //当前操作任务ID
const requirementMsg = ref(""); //审核评语
const reViewContentNumber = ref<any>(0);//审核评分
  const draftFiles = ref<any>([]);//该需求所有的需求草稿地址
const baseUrl = ref(import.meta.env.VITE_SERVE);//服务器地址
const urls = ref<any>([]);//待下载文件地址

////   待审核数据区域数据   ////
const allReviewRequirement = ref<any>([]); //我创建的所有需求
const reviewNameOptions = ref<any>([]); //技术负责人下拉列表
const isReviewName = ref("");//选中的技术负责人
const dialogReviewNameVisible = ref(false);//需求评分弹窗控件
const dialogInfoVisible = ref(false);//查看需求弹窗控件
const clearData = ref(false);//控制是否清空子组件数据
const dialogRecordVisible = ref(false);//控制查看审核记录弹窗控件
const recordData = ref<any>([]);//所有审核记录

// TODO 点击创建任务
const createRequirementClick = () => {
  router.push({
    path: "/requirement/create",
  });
};

// TODO 获取【我待审核的需求】数据
const getAllReviewRequirement = async () => {
  loading.value = true;

  const { data } = await GetEnterRequirement({
    projectTitle: searchFormData.value.projectTitle,
    beginTime:
      searchFormData.value.time === null ? null : searchFormData.value.time[0],
    endTime:
      searchFormData.value.time === null ? null : searchFormData.value.time[1],
  });

  if (data.code === 200 && data.data !== null) {
    allReviewRequirement.value = data.data
      .map((item: any) => {
        return {
          ID: item.ID,
          requirementCreateName: item.requirementCreateName,
          requirementName: item.requirementName,
          itemRequirementWorldDraft: item.itemRequirementWorldDraft,
          itemRequirementIsEnter: item.itemRequirementIsEnter,
          itemRequirementIsGetTest: item.itemRequirementIsGetTest,
          requirementContent: item.requirementContent,
          createAt: item.createAt,
          requirmentFatherStatus: item.requirmentFatherStatus,
          onlineTime: item.onlineTime,
          requirementBossName: item.requirementBossName,
          itemRequirementReview: item.itemRequirementReview,
        };
      }).filter((item: any) => item.requirmentFatherStatus !== 9);

    console.log("待审核需求：", allReviewRequirement.value);
    ElMessage.success(data.msg);
    loading.value = false;
    return;
  } else if (data.data === null && data.code === 200) {
    ElMessage.error("权限不足，无需审核！");
    allReviewRequirement.value = [];
    loading.value = false;
    return;
  } else {
    ElMessage.error(data.msg);
    loading.value = false;
    return;
  }
};

// 查看需求
const handleRowClick = async (id: number) => {
  console.log("查看需求:", id);
  dialogInfoVisible.value = true;
  isRequirementID.value = id;
};

// TODO 关闭主需求
// const closeFatherStatus = async (id: number) => {
//     console.log("关闭该需求id:", id)
//   await ElMessageBox.confirm("确认关闭该需求吗？", {
//     confirmButtonText: "确认",
//   }).catch(() => {
//     console.log("取消关闭该需求！");
//     return new Promise(() => {});
//   });

//   const { data } = await putCloseRequirementStatus({
//     requirementId: id,
//   });
//   if (data.code !== 200) {
//     ElMessage.warning(data.msg);
//     return;
//   } else {
//     await getAllReviewRequirement();
//   }
// };


// TODO 开启审核需求弹窗
const handleOpenDialog = (id: number) => {
    console.log(id)
  isRequirementID.value = id;
  dialogReviewVisible.value = true;
};

// TODO 确认选择技术负责人
// const handleReviewName = async () => {
//     console.log("--------------");
//     console.log({
//         itemRequirementId: isRequirementID.value,
//         nickName: isReviewName.value,
//         uuid: reviewNameOptions.value.find((item: any) => item.nickName === isReviewName.value).uuid
//     })
// }

// TODO 审核需求提交函数
const submitReview = async (val: any) => {
  const { data } = await PostReviewRequirementMsg({
    itemRequirementId: isRequirementID.value,
    reViewContent: requirementMsg.value.trim(),
    reViewContentNumber: reViewContentNumber.value,
    isEnter: val,
  });
  
  if (data.code === 200) {
    ElMessage.success(data.msg);
    clearData.value = true;
    dialogReviewVisible.value = false;
    requirementMsg.value = "";
    reViewContentNumber.value = 0;
    loading.value = true;
    await getAllReviewRequirement();
    loading.value = false;
    return;
  } else {
    ElMessage.error(data.msg);
    clearData.value = true;
    dialogReviewVisible.value = false;
    requirementMsg.value = "";
    reViewContentNumber.value = 0;
    isRequirementID.value = null;
    return;
  }
};

// TODO 查看审核不通过原因
const handleReviewEnterMsg = async (id: number) => {
  dialogRecordVisible.value = true;

  const { data } = await GetRequirementEnterMsg(id);

  if(data.code === 200) {
    recordData.value = data.data;
  } else {
    ElMessage.error(data.msg);
    return;
  }
};

// TODO 关闭【查看审核记录】弹窗
const handleCloseDiglog = () => {
  dialogRecordVisible.value = false;
  recordData.value = [];
};

// TODO 处理每次审核的需求草稿
const handleRecordFiles = (val: string) => {
  // 需求草稿地址
  if(val !== "") {
      draftFiles.value = val.split("|").map((url: string) => {
        return handleFileName(url);
         /*  return {
              url: `${baseUrl.value}${url}`,
              type: url.split(".").pop()
          } */
      });
      console.log("需求草稿地址", draftFiles.value);
  }
  return draftFiles.value;
};

// TODO 下载文件
/* const downloadFile = async (val: any, index: number) => {
    try {
        console.log("当前下载文件：", val);
        const link = document.createElement('a');
        link.href = val.url;

        link.download = `${index+1}.${val.type}`;
        console.log("下载文件名：", link.download);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(val.url);

    } catch (error) {
        console.log("下载文件失败：", error);
        alert("下载文件失败，请检查链接的合法性和网络连接。");
    }
}; */

// TODO 审核需求功能
const handleReview = async (val: any) => {
  console.log("操作类型：", val);
  // 不通过
  if(val === 2) {
    if(requirementMsg.value == "") {
      ElMessage.warning("必须填写评语");
      return;
    } else {
      ElMessage.success("校验通过");
      await submitReview(val);
    }
  } else if(val === 3) {
    // 审核通过
    if(reViewContentNumber.value === null || reViewContentNumber.value === 0 || requirementMsg.value == "") {
      ElMessage.warning("必须填写评语和评分");
      return;
    } else {
      ElMessage.success("校验通过");
      await submitReview(val);
    }
  };

  // if (val === 3) {
  //   if(reViewContentNumber.value === null || requirementMsg.value == "") {
  //     ElMessage.warning("必须填写评语和评分");
  //     return;
  //   } else {
  //     ElMessage.success("校验通过");
  //   }
  // }

  // 审核通过
  // if (val === 3 && requirementMsg.value === "" && reViewContentNumber.value === undefined) {
  //   ElMessage.warning("必须填写评语和评分");
  //   return;
  // } else {
  //   ElMessage.success("校验通过");
  // };


  //  else {
    // const { data } = await PostReviewRequirementMsg({
    //   itemRequirementId: isRequirementID.value,
    //   reViewContent: requirementMsg.value,
    //   reViewContentNumber: reViewContentNumber.value,
    //   isEnter: val,
    // });
  
    // if (data.code === 200) {
    //   ElMessage.success(data.msg);
    //   // 审核通过
    //   // if(val === 3) {
    //   //     dialogReviewNameVisible.value = true;
    //   // }
  
    //   clearData.value = true;
    //   dialogReviewVisible.value = false;
    //   requirementMsg.value = "";
    //   loading.value = true;
    //   await getAllReviewRequirement();
    //   loading.value = false;
    //   return;
    // } else {
    //   ElMessage.error(data.msg);
    //   clearData.value = true;
    //   dialogReviewVisible.value = false;
    //   requirementMsg.value = "";
    //   return;
    // }
  };

  // if(requirementMsg.value !== "" && reViewContentNumber.value !== null) {
  //   const { data } = await PostReviewRequirementMsg({
  //     itemRequirementId: isRequirementID.value,
  //     reViewContent: requirementMsg.value,
  //     reViewContentNumber: reViewContentNumber.value,
  //     isEnter: val,
  //   });
  
  //   if (data.code === 200) {
  //     // ElMessage.success(data.msg);
  //     // 审核通过
  //     // if(val === 3) {
  //     //     dialogReviewNameVisible.value = true;
  //     // }
  
  //     clearData.value = true;
  //     dialogReviewVisible.value = false;
  //     requirementMsg.value = "";
  //     loading.value = true;
  //     await getAllReviewRequirement();
  //     loading.value = false;
  //     return;
  //   } else {
  //     ElMessage.error(data.msg);
  //     clearData.value = true;
  //     dialogReviewVisible.value = false;
  //     requirementMsg.value = "";
  //     return;
  //   }
  // } else {
  //  ElMessage.warning("必须填写评语和评分。");
  //  return;
  // }
// };

// TODO 下载附件功能:有问题，只能下载数组中最后一个文件
// const handleDownLoad = async (url: string) => {
//     console.log(import.meta.env.VITE_SERVE);
//     urls.value = url.split("|").map((path: string) => `${baseUrl.value}${path}`);
//     console.log("处理后的附件地址：", urls.value);

//     urls.value.forEach((path: string) => {
//         downloadFile(path);
//     });
// }

// // TODO 下载文件
// const downloadFile = async (url: string) => {
//     try {
//         console.log("当前下载文件：", url);
//         const link = document.createElement('a');
//         link.href = url;

//         link.download = url.split("/").toString();
//         document.body.appendChild(link);
//         link.click();
//         document.body.removeChild(link);
//         URL.revokeObjectURL(url);

//     } catch (error) {
//         console.log("下载文件失败：", error);
//         alert("下载文件失败，请检查链接的合法性和网络连接。");
//     }
// };

// TODO 点击标题查询需求
// const ClickRequirement = async (id: number) => {
//   console.log(`查询需求：${id}`);
//   const { data } = await PostRequirement({
//     id: id,
//   });
//   console.log(data);
// };

// // TODO 处理开发周期时间的方法
// const handleOnlineTime = (val: any) => {
//   if (val == null || val == "") {
//     return "";
//   } else {
//     return tableTimeDate(val);
//   }
// };

// 刷新fatherStatus
// const updateFatherStatus = async (id: number) => {
//   const { data } = await getNewFatherRequirementStatus({
//     requirementId: id,
//   });

//   if (data.code !== 200) {
//     ElMessage.error(data.msg);
//     return;
//   }
// };

onMounted(async () => {
//   await useCommonStore.getAllRoleUsersList("555|999");
//   reviewNameOptions.value = useCommonStore.$state.allRoleUserList;
//   console.log(reviewNameOptions.value);
  getAllReviewRequirement();
});
</script>

<style lang="scss" scoped>
.content-container {
  background-color: white;
  display: flex;
  flex-direction: column;
  padding: 10px;

  // TODO 搜索区域
  .search-wrap {
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #dcdfe6;

    .search-wrap-item {
      margin-right: 20px;
      min-width: 200px;
      font-weight: bold;
      font-size: 24px;
      font-family: Arial, Helvetica, sans-serif;
      color: #000;
    }
  }

    // TODO 数据区域
    .table-requirement-name:hover,
    .table-download:hover {
        color: #409EFF;
        cursor: pointer;
    }

    // TODO 查看审核记录弹窗
    .record-title {
    display: flex;
    flex-direction: row;
    padding: 5px 10px;
    margin-bottom: 10px;
    background-color: #f0f0f0;
    border-radius: 2px;
    p {
      margin-right: 20px;
    }

  }
  // 需求草稿
  .info-file-box {
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-direction: row;
    margin: 10px 0 0;
    .info-content-title {
        width: 100px;
        padding: 0 10px;
    }

    .info-file-ul {
        width: calc(100% - 70px);
        text-align: left;
        display: flex;
        flex-direction: row;
        .info-file-item {
            width: 100px;
            margin-right: 10px;
            color: blue;
        }
        .info-file-item:hover {
            color: #409EFF;
            cursor: pointer;
        }
    }
  }
}
</style>
